use std::sync::Arc;

use ntex::web::types::{Json, Path, State};

use crate::{
    errors::CustomError,
    models::{comment::Comment, user::UserInfo},
    AppState,
};

// get current article all comments by article id (include user info)
pub async fn get_comments_for_article(
    article_id: Path<(u32)>,
    state: State<Arc<AppState>>,
) -> Result<Json<Vec<Comment>>, CustomError> {
    let db_pool = &state.db_pool;

    let article_id = article_id.0;

    // search all comment at specify article
    let comments = sqlx::query!(
        "SELECT comments.id, comments.user_id, comments.content, comments.date, users.name, users.avatar_url FROM comments JOIN users ON comments.user_id = users.id WHERE comments.article = $1", article_id as i32
  )
  .fetch_all(db_pool)
  .await?
  .iter()
  .map(|i| Comment {
    id: Some(i.id as u32),
    user: Some(UserInfo {
      id: i.user_id as u32,
      login: i.name.clone(),
      avatar_url: i.avatar_url.clone(),
      is_admin: i.user_id == 6969, // TODO: this 6969 maybe change your own
    }),

    content: i.content.clone(),
    date: Some(i.date),
    article: None,
  })
  .collect::<Vec<Comment>>();

    Ok(Json(comments))
}
